package cn.coldleaf.wiki.utils;

import java.util.Arrays;
import java.util.RandomAccess;

/**
 * @datetime 2023/10/21 下午3:02
 * @user cold
 **/
public class ByteBuffer implements RandomAccess,Cloneable, java.io.Serializable {
    private byte [] buffer;
    private int size;
    public ByteBuffer(int initialCapacity){
        this.buffer = new byte[initialCapacity];
        this.size = 0;
    }
    public ByteBuffer(){
        this(10);
    }
    public int size(){
        return this.size;
    }

    public void add(byte element){
        checkCapacity(1);
        buffer[size++] = element;
    }
    public void addAll(byte [] elements){
        if (elements == null || elements.length == 0){
            return;
        }
        checkCapacity(elements.length);
        for (byte element : elements) {
            buffer[size++] = element;
        }
    }

    public byte[] array(){
        byte [] result = new byte[size];
        System.arraycopy(buffer,0,result,0,size);
        return result;
    }

    private void checkCapacity(int count){
        if (buffer.length < size + count){//扩容
            byte [] target = new byte[buffer.length + (buffer.length + count) / 2];
            System.arraycopy(buffer,0,target,0,buffer.length);
            System.out.println("触发扩容，扩充前长度:["+buffer.length+"];扩充后长度:["+target.length+"]");
            buffer = target;
        }
    }

    public static void main(String[] args) {
        ByteBuffer buffer = new ByteBuffer();
        int size = 0;
        for (int i = -128; i < 129; i++) {
            buffer.add((byte)i);
            size ++;
        }
        System.out.println("应有长度:["+size+"]实际长度:["+buffer.size()+"]");
        byte [] tmp = buffer.array();
        System.out.println("转数组后长度:["+tmp.length+"];最后一个元素是:["+tmp[tmp.length -1]+"]");
        System.out.print("内部元素:[");
        for (int i = 0; i < tmp.length; i++) {
            System.out.print(tmp[i]);
            if (i < tmp.length -1){
                System.out.print(",");
            }
        }
    }
}
